package com.Questions.DFS;

public class leetcode270 {
    public int closestValue(TreeNode root, double target) {

        double[] res=new double[2];
        res[0]=Double.MAX_VALUE;
        res[1]=Double.MAX_VALUE;
        double[] ans=nextNum(root,target,res);
        return (int)ans[0];
    }

    public double[] nextNum(TreeNode root,double target,double[] res){
        if(root==null){
            return res;
        }
        if(Math.abs(root.val-target)<res[1]){
            res[1]=Math.abs(root.val-target);
            res[0]=root.val;
        }else if(Math.abs(root.val-target)==res[1]){
            res[0]=Math.min(root.val,res[0]);
        }

        nextNum(root.left,target,res);
        nextNum(root.right,target,res);

        return res;
    }
}
